<?php


namespace app\api\controller;


use think\exception\ValidateException;
use app\api\BaseController;
class CarNumber extends BaseController
{
    public $middleware = [\app\api\middleware\AuthCheck::class];
    public function create(){
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(\app\api\validate\CarNumber::class)->scene('create')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $saveData['user_id']=$this->request->userId;
            $saveData['car_number']=$input['car_number'];
            $saveData['car_name']=$input['car_name'];
            $res=(new \app\admin\model\CarNumber())->where($saveData)->findOrEmpty()->toArray();
            if($res){
                return json(['status' => 'error', 'message' => '该车牌号已存在']);
            }
            $saveData['add_time']=date('Y-m-d H:i:s');
            (new \app\admin\model\CarNumber())->insertGetId($saveData);
            return json(['status' => 'success', 'message' => '添加成功', 'data' => []]);
        }
    }
    public function delete(){
        $id=input('post.id');
        if(empty($id)){
            return json(['status' => 'error', 'message' => '请选择车牌号']);
        }
        $res=(new \app\admin\model\CarNumber())->where('id',$id)->delete();
        if($res){
            return json(['status' => 'success', 'message' => '操作成功', 'data' => []]);
        }else{
            return json(['status' => 'error', 'message' => '操作异常,请勿重复操作', 'data' => []]);
        }
    }
    public function index()
    {
        if ($this->request->isPost()) {
            $page=input("post.page");
            $page_size=input("post.page_size");
            $page=$page?$page:1;
            $page_size=$page_size?$page_size:15;
            $count =(new \app\admin\model\CarNumber())->where('user_id', $this->request->userId)->count();
            $list =(new \app\admin\model\CarNumber())->where('user_id', $this->request->userId)->page($page, $page_size)->order('id desc')->select()->toArray();
            $totalPages = ceil($count / $page_size);
            $data['list']=$list;
            $data['count']=$count;
            $data['totalPages']=$totalPages;
            return json(["status" => "success", "message" => "请求成功", "data" => $data]);
        }
    }
}